import datetime
import sys, time, os, signal
import numpy as np
from PIL import Image, ImageDraw
import cv2
from vncdotool import api
import uuid

def record(output, host, port, fps, password=None):
    print("Start Recording")
    pid = 0
    retval = 0
    cli = api.connect(host+"::"+port, password=password, timeout=10)
    cli.refreshScreen(False)
    videodims = cli.screen.size
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    # fourcc = 0x00000021
    frame = int(fps)
    video = cv2.VideoWriter(output, fourcc, frame, videodims)
    try:
        def sigint_handler(sig, frame):
            raise KeyboardInterrupt

        signal.signal(signal.SIGINT, sigint_handler)
        try:
            while 1:
                elapse = int()
                start = time.time()
                for i in range(0, frame):
                    # print(datetime.datetime.now(),"start")
                    cli.refreshScreen()
                    imtemp = cli.screen.copy()
                    video.write(cv2.cvtColor(np.array(imtemp), cv2.COLOR_RGB2BGR))
                    # print(datetime.datetime.now(),"stop")
                stop = time.time()
                elapse = stop - start
                print("Frame Process : " + str(elapse))
                if elapse < 1:
                    time.sleep(1 - elapse)
        finally:
            # p_stop = time.time()
            video.release()
            cli.disconnect()
            print("Stop Recording")
            tmp_mp4 = str(uuid.uuid4())+".mp4"
            cmd = "ffmpeg -i %(source)s -vcodec h264 %(dest)s && mv %(dest)s %(source)s" %{"source":output, "dest":tmp_mp4}
            os.system(cmd)
            with open("/var/log/convert_mp4.log","w+") as f:
                f.write(cmd)
    except KeyboardInterrupt:
        pass
    if pid:
        os.killpg(os.getpgid(pid), signal.SIGTERM)

    return retval


def main(args):
    # python3 vnc2mp4.py output.mp4 host::port fps password[OPTIONAL]
    if len(args) < 3:
        print("Missing parameters")
        sys.exit()
    else:
        output = args[0]
        host = args[1]
        port = args[2]
        fps = args[3]
        password = None
        if len(args) == 5: password = args[4]
    record(output=output, host=host,port=port,  fps=fps, password=password)


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
